"""
AI服务模块 - 整合文本处理和相似度匹配功能
"""
from typing import List, Dict, Tuple, Optional
from sqlalchemy.orm import Session
from app.ai.text_processor import text_processor
from app.ai.similarity_matcher import similarity_matcher
from app import crud

class AIService:
    """AI服务类"""
    
    def __init__(self):
        """初始化AI服务"""
        self.text_processor = text_processor
        self.similarity_matcher = similarity_matcher
    
    def analyze_text(self, text: str) -> Dict:
        """
        分析文本内容，提取关键信息
        
        Args:
            text: 要分析的文本
            
        Returns:
            分析结果字典
        """
        if not text:
            return {
                "keywords": [],
                "word_count": 0,
                "processed_text": ""
            }
        
        # 文本预处理
        processed_text = self.text_processor.preprocess_text(text)
        
        # 提取关键词
        keywords = self.text_processor.extract_keywords(text, topK=10)
        
        # 统计词数
        word_count = len(self.text_processor.segment_text(text))
        
        return {
            "keywords": keywords,
            "word_count": word_count,
            "processed_text": processed_text
        }
    
    def match_similar_cases(self, query: str, db: Session, category: Optional[str] = None, limit: int = 10) -> List[Tuple[Dict, float]]:
        """
        匹配相似案例
        
        Args:
            query: 查询文本
            db: 数据库会话
            category: 案例分类（可选）
            limit: 返回结果数量限制
            
        Returns:
            相似案例列表，每个元素为(案例字典, 相似度)的元组
        """
        if not query:
            return []
        
        # 从数据库获取案例
        cases = crud.case.get_cases(db, category=category)
        
        if not cases:
            return []
        
        # 转换案例为字典格式
        case_dicts = []
        for case in cases:
            case_dict = {
                "id": case.id,
                "title": case.title,
                "description": case.description,
                "solution": case.solution,
                "keywords": case.keywords,
                "category": case.category
            }
            case_dicts.append(case_dict)
        
        # 查找相似案例
        similar_cases = self.similarity_matcher.find_similar_cases(query, case_dicts, top_k=limit)
        
        return similar_cases
    
    def get_case_recommendations(self, issue_description: str, db: Session, limit: int = 5) -> List[Dict]:
        """
        获取案例推荐
        
        Args:
            issue_description: 问题描述
            db: 数据库会话
            limit: 返回推荐数量
            
        Returns:
            推荐案例列表
        """
        # 匹配相似案例
        similar_cases = self.match_similar_cases(issue_description, db, limit=limit)
        
        # 格式化推荐结果
        recommendations = []
        for case, similarity in similar_cases:
            recommendation = {
                "case_id": case["id"],
                "title": case["title"],
                "similarity_score": round(similarity, 4),
                "category": case["category"]
            }
            recommendations.append(recommendation)
        
        return recommendations
    
    def extract_problem_info(self, description: str) -> Dict:
        """
        从问题描述中提取信息
        
        Args:
            description: 问题描述
            
        Returns:
            提取的信息字典
        """
        # 文本分析
        analysis = self.analyze_text(description)
        
        # 提取可能的设备型号（简单的正则匹配）
        import re
        model_patterns = [
            r'[A-Z]{1,3}\d{3,}[A-Z]?',  # 匹配类似ABC1234D的型号
            r'[A-Z]\d{2,}[A-Z]{1,2}',   # 匹配类似A123BC的型号
        ]
        
        models = []
        for pattern in model_patterns:
            matches = re.findall(pattern, description, re.IGNORECASE)
            models.extend(matches)
        
        # 提取可能的故障现象关键词
        fault_keywords = ["无法", "不能", "失效", "损坏", "故障", "异常", "错误", "问题"]
        detected_faults = [kw for kw in fault_keywords if kw in description]
        
        return {
            "keywords": analysis["keywords"],
            "models": list(set(models)),
            "fault_indicators": detected_faults,
            "word_count": analysis["word_count"]
        }

# 创建全局实例
ai_service = AIService()